/*
 *          AccumOmniLight.glsl
 *
 */

//------------------------------------------------------------------------------


-- Vertex


// IN
layout(location = 0) in vec4 inPosition;

// OUT
smooth out vec3 vEyeDirVS;

// UNIFORM
uniform mat4 uModelViewProjMatrix;
uniform mat4 uModelViewMatrix;
//uniform mat4 uInvProjMatrix;

uniform vec4 uDebugLight;

void main()
{
  vec4 pos = vec4( inPosition.xyz * uDebugLight.a, 1.0f );
  
  gl_Position = uModelViewProjMatrix * pos;

  // Unormalized view-Space 'view to vert' ray
  vEyeDirVS = (uModelViewMatrix * pos).xyz; 
}


--

//------------------------------------------------------------------------------

-- Fragment


in vec3 vEyeDirVS;

// OUT
layout(location = 0) out vec4 fragColor;

// UNIFORM
uniform sampler2D uNormalBuffer;
uniform sampler2DShadow uDepthBuffer; //
uniform vec2 uLinearParams;

uniform vec4 uDebugLight;
uniform vec3 uLightColor = vec3(1.0f);

void main()
{
  // XXX ~

  vec2 uv = gl_FragCoord.xy / textureSize( uNormalBuffer, 0).xy;
  
  vec3 normalVS = normalize( texture( uNormalBuffer, uv).rgb );
  
  
  // Depth (post-Proj space)
  float depth = texture( uDepthBuffer, vec3( uv, 0.0f) );
    
  // linearize depth
  float linearDepth = uLinearParams.y / (depth - uLinearParams.x);
  
  // Position (view space)
  vec3 viewRay = (vEyeDirVS / -vEyeDirVS.z);  
  vec3 positionVS = linearDepth * viewRay;
  
  vec3 toLight = uDebugLight.xyz - positionVS;
  
  float len = length( toLight );

  // Simple linear attenuation model
  if (len > uDebugLight.a ) {fragColor = vec4(0.0f); return;}
  toLight /= len;
  
  float diffuse = max( 0.0f, dot( toLight, normalVS));
    
  //vec3 packedNormal = 0.5f*(normalVS + vec3(1.0f));
  fragColor.rgb = uLightColor * diffuse;
  fragColor.a   = 1.0f;
}

